package com.yuanjun.product.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.yuanjun.product.interceptor.CrossInterceptor;
import com.yuanjun.product.interceptor.SecurityCheckInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class BaseMvcConfig {

    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public SecurityCheckInterceptor securityCheckInterceptor() {
        return new SecurityCheckInterceptor();
    }

    @Bean
    public CrossInterceptor crossInterceptor() {
        return new CrossInterceptor();
    }


    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
        CrossInterceptor crossInterceptor = crossInterceptor();
        SecurityCheckInterceptor securityCheckInterceptor = securityCheckInterceptor();
        return new WebMvcConfigurerAdapter() {
            @Override
            public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
                FastJsonHttpMessageConverter jsonConverter = new FastJsonHttpMessageConverter();
                List<MediaType> listType = new ArrayList<>();
                listType.add(MediaType.APPLICATION_JSON);
                listType.add(MediaType.TEXT_HTML);
                jsonConverter.setSupportedMediaTypes(listType);
                converters.add(jsonConverter);
            }

            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(crossInterceptor).addPathPatterns("/**");
                registry.addInterceptor(securityCheckInterceptor)
                        .addPathPatterns("/**")
                        .excludePathPatterns("/login", "/list", "/swagger-resources/**", "/webjars/**", "/swagger-ui**");
                super.addInterceptors(registry);
            }

            @Override
            public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
                configurer.enable();
            }
        };
    }

}
